﻿namespace IBTrader.Modules.Export
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Xml;

    class XmlInterfaceSerializer
    {
        private Type type;
        public XmlInterfaceSerializer(Type type)
        {
            this.type = type;
        }
        public void Serialize(TextWriter txtWriter, object obj)
        {
            XmlTextWriter writer = new XmlTextWriter(txtWriter);
            writer.Formatting = Formatting.Indented;
            Serialize(writer, obj);
        }
        public void Serialize(Stream stream, object obj)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.Default);
            writer.Formatting = Formatting.Indented;
            Serialize(writer, obj);
        }
        public void Serialize(XmlTextWriter writer, object obj)
        {
            writer.WriteStartElement(type.Name);
            foreach (PropertyInfo pi in type.GetProperties())
            {
                writer.WriteStartElement(pi.Name);
                object val = pi.GetValue(obj, null);
                if (val != null)
                {
                    writer.WriteValue(pi.GetValue(obj, null));
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
        public void Deserialize(XmlTextReader reader, object obj)
        {
            reader.ReadStartElement();
            foreach (PropertyInfo pi in type.GetProperties())
            {
                reader.ReadStartElement();
                object val = reader.ReadElementContentAsObject();
                pi.SetValue(obj, val, null);
                reader.ReadEndElement();
            }
            reader.ReadEndElement();
        }
    }
}
